<template>
  <div class="select-exchange bcl-bg">
    <!-- 按钮 -->
    <div class="flex flex-cc click" @click="exchangeVisible = true">
      <div class="fz-12 cl-basic ml-5 mr-5">
        {{ exchanges[0][defaultIndex].label }}
      </div>
      <van-icon name="arrow-down" color="#8e8e8e" :size="12"></van-icon>
    </div>

    <!-- 语言选择 -->
    <van-popup
      teleport="body"
      position="bottom"
      round
      v-model:show="exchangeVisible"
    >
      <van-picker
        :title="$t('选择兑换类型')"
        :cancel-button-text="$t('取消')"
        :confirm-button-text="$t('确定')"
        :columns="exchanges"
        :columns-field-names="{
          text: 'label',
          values: 'value',
        }"
        @cancel="exchangeVisible = false"
        @confirm="onSelectChange"
      ></van-picker>
    </van-popup>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const emit = defineEmits(['select-exchange'])

// 合约列表
const contracts = ref({
  PUSD: {
    name: 'PUSD',
    address: import.meta.env.VITE_PUSD_CONTRACT_ADDRESS,
  },
  'PUSD-HASH': {
    name: 'PUSD-HASH',
    address: import.meta.env.VITE_PUSD_HASH_CONTRACT_ADDRESS,
  },
  PC: {
    name: 'PC',
    address: import.meta.env.VITE_PC_CONTRACT_ADDRESS,
  },
  'PC-HASH': {
    name: 'PC-HASH',
    address: import.meta.env.VITE_PC_HASH_CONTRACT_ADDRESS,
  },
})

// 兑换列表
const exchanges = ref([
  [
    {
      label: 'PUSD -> PUSD-HASH',
      sender: contracts.value['PUSD'],
      receiver: contracts.value['PUSD-HASH'],
      value: 0,
    },
    {
      label: 'PUSD-HASH -> PUSD',
      sender: contracts.value['PUSD-HASH'],
      receiver: contracts.value['PUSD'],
      value: 1,
    },
    {
      label: 'PC - PC-HASH',
      sender: contracts.value['PC'],
      receiver: contracts.value['PC-HASH'],
      value: 2,
    },
    {
      label: 'PC-HASH - PC',
      sender: contracts.value['PC-HASH'],
      receiver: contracts.value['PC'],
      value: 3,
    },
  ],
])
const exchangeVisible = ref(false)

// 默认选择
const defaultIndex = ref(Number(localStorage.getItem('exchangeIndex') || '0'))
onSelectChange({ selectedIndexes: [defaultIndex.value] })

// 选择兑换类型
function onSelectChange({ selectedIndexes }) {
  const index = selectedIndexes[0]
  defaultIndex.value = index
  localStorage.setItem('exchangeIndex', index)
  emit('select-exchange', exchanges.value[0][index])
  exchangeVisible.value = false
}
</script>

<style lang="scss" scoped>
.select-exchange {
  display: inline-block;
  padding: 0 5px;
  border-radius: 100px;
  height: 22px;
  line-height: 22px;
}
</style>
